package api.goods;

import bean.Goods;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import dao.GoodsDao;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class AddGoodsServlet  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//       增加商品
//        第一步：获取前端发来的json数据
        req.setCharacterEncoding("UTF-8");
//        String goodsStr=req.getParameter("goods");这是get方法发来的请求参数可以这个获取，但是post方法不行
        JSONObject goodsJSONObject=GetRequestJsonUtils.getRequestJsonObject(req);
        String goodsStr=goodsJSONObject.getString("goods");
//        第二步：用fastjson将这个json数据转换成Goods对象
        Goods goods=JSON.parseObject(goodsStr, Goods.class);
        boolean isAdd=false;
        try{
            isAdd=GoodsDao.addGoods(goods);
        }catch (SQLException e){
            e.printStackTrace();
            isAdd=false;
        }
        Response build=null;
        if(isAdd){//插入成功返回浏览器一段json数据
            build = Response.build(ResponseCode.SUCCESS);
        }else {//插入失败返回浏览器一段json数据
            build = Response.build(ResponseCode.ERROR);
        }
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());

    }
}
